package com.mogist.hqc.module.community.ui

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Handler
import android.os.Message
import android.support.v7.widget.GridLayoutManager
import android.view.View
import butterknife.OnClick
import butterknife.Optional
import com.chad.library.adapter.base.BaseQuickAdapter
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.response.UriData
import com.mogist.hqc.module.community.adapter.CommunityAddAdapter
import com.mogist.hqc.module.community.contract.CommunityCreateContract
import com.mogist.hqc.module.community.presenter.CommunityCreatePresenter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.oss.OssManager
import com.mogist.hqc.util.Constant
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import io.valuesfeng.picker.Picker
import io.valuesfeng.picker.engine.GlideEngine
import io.valuesfeng.picker.utils.PicturePickerUtils
import kotlinx.android.synthetic.main.activity_community_create.*
import talex.zsw.basecore.interfaces.OnSimpleListener
import talex.zsw.basecore.util.*
import talex.zsw.basecore.view.dialog.sweetalertdialog.SweetAlertDialog
import talex.zsw.basecore.view.other.RxToast
import talex.zsw.basecore.view.recyleview.DividerGridItemDecoration
import java.lang.ref.WeakReference

/**
 * 作用：微社区 - 新建
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class CommunityCreateActivity : BaseMVPActivity<CommunityCreateContract.Presenter>(), CommunityCreateContract.View
{
    var title = ""
    var content = ""
    var imgList: ArrayList<String> = arrayListOf()

    override fun initArgs(intent: Intent)
    {
    }

    override fun initView()
    {
        setContentView(R.layout.activity_community_create)
        mPresenter = CommunityCreatePresenter(this)
    }

    override fun initData()
    {
        initRecyclerView()
        listData.add(UriData())
        adapter.replaceData(listData)
        OssManager.getInstance()
        weakHandler = WeakHandler(this@CommunityCreateActivity)
    }

    @Optional
    @OnClick(R.id.mTvCancel, R.id.mTvSure)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mTvCancel ->
                {
                    finish()
                }
                R.id.mTvSure   ->
                {
                    title =
                            mEtTitle.text.toString()
                                    .trim()
                    content =
                            mEtContent.text.toString()
                                    .trim()
                    if (RegTool.isEmpty(title))
                    {
                        RxToast.error("请输入标题")
                    }
                    else
                    {
                        if (mSelected.isEmpty())
                        {
                            RxToast.error("请至少选择一张图片提交")
                        }
                        else
                        {
                            sumPic = mSelected.size
                            uploadPos = 0
                            uploadImg()
                        }
                    }
                }
            }
        }
    }

    private fun upload()
    {
        val body = BaseModel(true)
        body.title = title
        body.content = content
        body.imgList =
                JsonTool.getJsonString(imgList)
                        .replace("[", "")
                        .replace("]", "")
                        .replace("\"", "")
        mPresenter.getData(HttpDto(Constant.COMMUNITY_UPLOAD, body).setErrorTitle("发布失败"))
    }

    override fun uploadSuccess()
    {
        RxToast.success("发布成功！请耐心等待审核通过")
        finish()
    }

    // --------------- RecyclerView ---------------
    private val adapter = CommunityAddAdapter()

    private fun initRecyclerView()
    {
        adapter.setOnItemClickListener { adapter, view, position ->
            PermissionHelper.check(OnSimpleListener {
                choosePic()
            }, PermissionConstants.CAMERA, PermissionConstants.STORAGE)
        }
        adapter.setOnItemChildClickListener { adapter, view, position ->
            if (!isFastClick)
            {
                listData.removeAt(position)
                if (listData.last().uri != null)
                {
                    listData.add(UriData())
                }
                mSelected.removeAt(position)
                adapter.replaceData(listData)
            }
        }
        adapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN)
        mRecyclerView.addItemDecoration(DividerGridItemDecoration(Color.TRANSPARENT))
        mRecyclerView.layoutManager = GridLayoutManager(this@CommunityCreateActivity, 4)
        mRecyclerView.adapter = adapter
    }

    // --------------- 图片获取 ---------------
    val REQUEST_CODE_CHOOSE = 10000
    private var mSelected: ArrayList<Uri> = arrayListOf()
    private var listData: ArrayList<UriData> = arrayListOf()
    private val IMG_COUNT = 8

    private fun choosePic()
    {
        Picker.from(this)
                .count(IMG_COUNT)
                .enableCamera(true)
                .resume(mSelected)
                .setEngine(GlideEngine())
                .forResult(REQUEST_CODE_CHOOSE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
    {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == Activity.RESULT_OK)
        {
            listData = arrayListOf()
            if (data != null)
            {
                mSelected = PicturePickerUtils.obtainResult(data) as ArrayList<Uri>
                for (u in mSelected)
                {
                    LogTool.ni(u.path)
                    listData.add(UriData(u))
                }
                if (mSelected.size < IMG_COUNT)
                {
                    listData.add(UriData())
                }
            }
            else
            {
                listData.add(UriData())
            }
            adapter.replaceData(listData)
        }
    }

    // --------------- 图片上传 ---------------
    private var uploadPos = 0
    private var sumPic = -1
    private var imgErrorList: ArrayList<Int> = arrayListOf()
    private fun uploadImg()
    {
        if (uploadPos >= sumPic)
        {
            if (imgList.size == sumPic)
            {
                upload()
            }
            else
            {
                showDialog(SweetAlertDialog.WARNING_TYPE,
                           "部分图片上传失败,是否重试失败图片？",
                           "成功：${imgList.size}/$sumPic",
                           "重试失败",
                           "立即提交",
                           {
                               uploadPos = 0
                               uploadImg()
                           },
                           {
                               upload()
                           })
            }
        }
        else
        {
            if (listData[uploadPos].isUploaded)
            {
                weakHandler?.sendEmptyMessage(0)
            }
            else
            {
                uploadNext(listData[uploadPos])
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun uploadNext(data: UriData)
    {
        showDialog(SweetAlertDialog.PROGRESS_TYPE, "正在提交第${uploadPos + 1}/${sumPic}张图片,", "")
        Observable.just(data)
                .subscribeOn(Schedulers.io())
                .map { v ->
                    BitmapTool.getBitmap(v.uri, this@CommunityCreateActivity)
                }
                .subscribe { bitmap ->
                    OssManager.getInstance()
                            .upload(1, bitmap, object : OssManager.OnUploadListener
                            {
                                override fun onProgress(position: Int, currentSize: Long, totalSize: Long)
                                {
                                    LogTool.ni("position = $position  进度 = $currentSize /$totalSize")
                                }

                                override fun onSuccess(position: Int, imageUrl: String?)
                                {
                                    LogTool.ni("第${position}个成功 imageUrl = " + imageUrl)
                                    imgList.add(imageUrl.toString())
                                    listData[uploadPos].isUploaded = true
                                    weakHandler?.sendEmptyMessage(0)
                                }

                                override fun onFailure(position: Int)
                                {
                                    LogTool.ni("失败的position = " + position)
                                    imgErrorList.add(uploadPos)
                                    weakHandler?.sendEmptyMessage(0)
                                }
                            })
                }
    }

    override fun onDestroy()
    {
        weakHandler?.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    // --------------- Handler弱引用 ---------------
    private var weakHandler: WeakHandler? = null

    private class WeakHandler(activity: CommunityCreateActivity) : Handler()
    {
        private val weakReference: WeakReference<CommunityCreateActivity>

        init
        {
            weakReference = WeakReference(activity)
        }

        override fun handleMessage(msg: Message)
        {
            val activity = weakReference.get()
            if (activity != null)
            {
                when (msg.what)
                {
                    0 ->
                    {
                        activity.uploadPos++
                        activity.uploadImg()
                    }
                }
            }
        }
    }
}
